package com.situ.gym.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.situ.gym.pojo.Admin;
import com.situ.gym.pojo.query.AdminQuery;
import com.situ.gym.service.IAdminService;
import com.situ.gym.util.JwtUtil;
import com.situ.gym.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Gao
 * @since 2025-07-09
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    //注入过来service
    @Autowired
    private IAdminService adminService;

    @PostMapping("/login")
    public Result login(@RequestBody Admin admin) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", admin.getName());
        queryWrapper.eq("password", admin.getPassword());
        Admin loginAdmin = adminService.getOne(queryWrapper);
        if (loginAdmin == null) {
            return Result.error("用户名或密码错误");
        }

        //判断用户的status是不是禁用
        if (loginAdmin.getStatus() == 0) {
            return Result.error("该用户已经被禁用");
        }

        //登录成功
        Map<String, Object> map = new HashMap<>();
        map.put("id", loginAdmin.getId());
        map.put("name", loginAdmin.getName());
        String token = JwtUtil.createToken(map);

        return Result.ok("登录成功", token);
    }


    //Restful    GET(查找)、POST(添加)、DELETE(删除)、PUT(修改)
    @GetMapping("/list")
    public Result list(AdminQuery adminQuery) {
        IPage<Admin> page = adminService.list(adminQuery);
        return Result.ok(page);
    }

    // /admin/deleteById/12
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        adminService.removeById(id);
        return Result.ok("删除成功");
    }

    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids) {
        adminService.removeBatchByIds(Arrays.asList(ids));
        return Result.ok("删除成功");
    }

    @PostMapping("/add")
    public Result add(@RequestBody Admin admin) {
        adminService.save(admin);
        return Result.ok("添加成功");
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Admin admin = adminService.getById(id);
        return Result.ok(admin);
    }

    @PutMapping("/update")
    public Result update(@RequestBody Admin admin) {
        // update admin set name='zhangsn',age=23 where id=1
        adminService.updateById(admin);
        return Result.ok("修改成功");
    }

    @RequestMapping("/selectAll")
    public List<Admin> selectAll() {
        List<Admin> list = adminService.selectAll();
        return list;
    }



}

